define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

  var Controller = {
    index: function () {
      // 初始化表格参数配置
      Table.api.init();
      $(document).on("click", ".btn-config", function () {
        Fast.api.open('wx/wxorder/config', '提分超市订单', $(this).data() || {});
      });
      //绑定事件
      $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        var panel = $($(this).attr("href"));
        if (panel.size() > 0) {
          Controller.table[panel.attr("id")].call(this);
          $(this).on('click', function (e) {
            $($(this).attr("href")).find(".btn-refresh").trigger("click");
          });
        }
        //移除绑定的事件
        $(this).unbind('shown.bs.tab');
      });

      //必须默认触发shown.bs.tab事件
      $('ul.nav-tabs li.active a[data-toggle="tab"]').trigger("shown.bs.tab");
    },
    table: {
      first: function () {
        Table.api.init({
          extend: {
            index_url: 'wx/wxorder/index',
            add_url: 'wx/wxorder/add',
            edit_url: 'wx/wxorder/edit',
            del_url: 'wx/wxorder/del',
            multi_url: 'wx/wxorder/multi',
            import_url: 'wx/wxorder/import/ids/'+ids,
            finance_url: 'wx/wxorder/finance',
            config_url: 'wx/wxorder/config',
            become_url: 'wx/wxorder/become',
            becomes_url: 'wx/wxorder/becomes',
            second: 'first',
          }
        });
        // 表格1
        var table1 = $("#table1");
        //当表格数据加载完成时
        table1.on('load-success.bs.table', function (e, data) {
          //这里可以获取从服务端获取的JSON数据
          //这里我们手动设置底部的值
          $("#money").text(data.extend.money);
          // $("#price").text(data.extend.price);
        });
        var id2 = ids;
        $(document).on("click", ".btn-become", function () {
          var ids = Table.api.selectedids(table1);
          layer.prompt({title: '输入申请作废的原因', formType: 2}, function(pass, index){
            Table.api.multi("become", ids, table1, {params: pass+':'+id2});
            layer.close(index);
          });
        });
        $(document).on("click", ".btn-becomes", function () {
          var that = this;
          var ids = Table.api.selectedids(table1);
          Layer.confirm('是否要作废此条数据！',
            {icon: 3, title: __('Warning'),  shadeClose: true},
            function (index) {
              Table.api.multi("becomes", ids, table1, that);
              Layer.close(index);
            }
          );
        });
        table1.bootstrapTable({
          url: 'wx/wxorder/index',
          toolbar: '#toolbar1',
          sortName: 'id',
          search: false,
          columns: [
            [
              {checkbox: true,formatter:function (value,row,index) {
                  if(row.state == 1 || row.state == 9)
                  {
                    return {
                      disabled: true
                    };
                  }
                }},
              {field: 'id', title: __('Id')},
              {field: 'state', title: __('审核状态'),searchList: stateList,formatter: function (value,row,index) {
                  return '<span class="btn btn-primary">'+row.state_text+'</span>';
                }},
              {field: 'reason', title: __('原因')},
              {field: 'info.agent_name', title: __('Info.agent_name')},
              {field: 'xdtime', title: __('Xdtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
              {field: 'order_sn', title: __('Order_sn')},
              {field: 'goods_name', title: __('商品'),formatter:function(value,row,index){
                  //cellStyle:Controller.api.formatter.css,
                  return '<span title='+row.goods_name+'>'+row.goods_name+'</span>';
                }},
              {field: 'gifts', title: __('Gifts')},
              {field: 'akg', title: __('重量')},
              {field: 'amount', title: __('Amount'), operate:'BETWEEN'},
              {field: 'receipt', title: __('Receipt')},
              {field: 'phone', title: __('Phone') },
              {field: 'address', title: __('Address')},
              {field: 'orderStatus', title: __('发货状态'),searchList: {"0":__('待发货'),"1":__('已发货')},formatter:function (value,row,index) {
                  if((row.status == 0 || row.status == 2 || row.status == 4) && row.orderStatus == 0)
                  {
                    return '<span class="btn btn-success">待发货</span>';
                  }
                  if(row.orderStatus == 1)
                  {
                    return '<span class="btn  btn-warning">已发货</span>';
                  }
                  return '<span class="btn">-</span>';
                }},
              {field: 'deliveryForm', title: __('快递方式')},
              {field: 'courierBut', title: __('快递单号') , operate: 'LIKE %...%', placeholder: '模糊搜索，*表示任意字符'},
              //启用时间段搜索
              {
                field: 'createtime',
                title: __('创建时间'),
                sortable: true,
                formatter: Table.api.formatter.datetime,
                operate: 'RANGE',
                addclass: 'datetimerange'
              },
              // {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate},
              //操作栏,默认有编辑、删除或排序按钮,可自定义配置buttons来扩展按钮
              {
                field: 'operate',
                width: "150px",
                title: __('Operate'),
                table: table1,
                events: Table.api.events.operate,
                buttons: [
                  {
                    name: 'detail',
                    title: __('订单详情查看'),
                    classname: 'btn btn-xs btn-primary btn-dialog',
                    icon: 'fa fa-list',
                    url: 'wx/wxorderinfo/index',
                  }
                ],
                formatter: Table.api.formatter.operate
              },
            ]
          ],
          queryParams: function (params) {
            //这里可以追加搜索条件
            var filter = JSON.parse(params.filter);
            var op = JSON.parse(params.op);
            if(ids){
              //这里可以动态赋值，比如从URL中获取admin_id的值，filter.admin_id=Fast.api.query('admin_id');
              filter.id = ids;
              op.id = "in";
            }
            params.filter = JSON.stringify(filter);
            params.op = JSON.stringify(op);
            return params;
          }
        });

        // 为表格1绑定事件
        Table.api.bindevent(table1);

      },
      second: function () {
        // 表格2
        var table2 = $("#table2");
        table2.bootstrapTable({
          url: 'wx/wxorder/index',
          extend: {
            index_url: '',
            add_url: '',
            edit_url: '',
            del_url: '',
            multi_url: '',
            msg_url: 'wx/wxorder/send',
            importwlx_url: 'wx/wxorder/importwlx',//下册快递单号导入
            importwl_url: 'wx/wxorder/importwl',//快递单号导入
            table: '',
          },
          toolbar: '#toolbar2',
          sortName: 'id',
          search: false,
          columns: [
            [
              // {checkbox: true},
              {field: 'id', title: __('Id')},
              {field: 'status', title: __('订单状态'),formatter:function (value,row,index) {
                  if(row.status == 1 || row.status == 3)
                  {
                    return '<span class="btn btn-success">'+row.status_text+'</span>';
                  }
                  if(row.status == 2 || row.status == 4)
                  {
                    return '<span class="btn  btn-warning">'+row.status_text+'</span>';
                  }
                  return '<span class="btn">'+row.status_text+'</span>';
                }},
              {field: 'state', title: __('审核状态'),searchList: stateList,formatter: function (value,row,index) {
                  return '<span class="btn btn-primary">'+row.state_text+'</span>';
                }},
              {field: 'info.agent_name', title: __('Info.agent_name')},
              {field: 'order_sn', title: __('Order_sn')},
              {field: 'xdtime', title: __('Xdtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
              {field: 'gifts', title: __('Gifts')},
              {field: 'akg', title: __('重量')},
              {field: 'amount', title: __('Amount'), operate:'BETWEEN'},
              {field: 'receipt', title: __('Receipt')},
              {field: 'phone', title: __('Phone')},
              {field: 'address', title: __('Address')},
              {field: 'orderStatus', title: __('发货状态'),searchList: {"0":__('待发货'),"1":__('已发货')},formatter:function (value,row,index) {
                  if((row.status == 0 || row.status == 2 || row.status == 4) && row.orderStatus == 0)
                  {
                    return '<span class="btn btn-success">待发货</span>';
                  }
                  if(row.orderStatus == 1)
                  {
                    return '<span class="btn  btn-warning">已发货</span>';
                  }
                  return '<span class="btn">-</span>';
                }},
              {field: 'deliveryForm', title: __('快递方式')},
              {field: 'courierBut', title: __('快递单号'), operate: 'LIKE %...%', placeholder: '模糊搜索，*表示任意字符'},
              //启用时间段搜索
              {
                field: 'createtime',
                title: __('创建时间'),
                sortable: true,
                formatter: Table.api.formatter.datetime,
                operate: 'RANGE',
                addclass: 'datetimerange'
              },
              {
                field: 'operate',
                width: "150px",
                title: __('Operate'),
                table: table2,
                events: Table.api.events.operate,
                buttons: [
                  {
                    name: 'detail',
                    title: __('订单详情查看'),
                    classname: 'btn btn-xs btn-primary btn-dialog',
                    icon: 'fa fa-list',
                    url: 'wx/wxorderinfo/index',
                  },
                  {
                    name: 'detail',
                    title: __('短信详情'),
                    classname: 'btn btn-xs btn-primary btn-dialog',
                    icon: 'fa fa-send',
                    url: 'wx/wxsms/index',
                  }
                ],
                formatter: Table.api.formatter.operate
              },
            ]
          ],
          queryParams: function (params) {
            //这里可以追加搜索条件
            var filter = JSON.parse(params.filter);
            var op = JSON.parse(params.op);
            if(ids){
              //这里可以动态赋值，比如从URL中获取admin_id的值，filter.admin_id=Fast.api.query('admin_id');
              filter.id = ids;
              op.id = "in";
            }
            params.filter = JSON.stringify(filter);
            params.op = JSON.stringify(op);
            return params;
          }
        });

        // 为表格2绑定事件
        Table.api.bindevent(table2);
        //导入
        require(['upload'], function (Upload) {

          //物流单号导入
          Upload.api.plupload($('.btn-importwlx'), function (data, ret) {
            Fast.api.ajax({
              url:'wx/wxorder/importwlx' ,
              data: {file: data.url},
            }, function (data, ret) {
              if(data.length >= 1){
                var htmlstr = '';
                data.forEach(function (element, index, array) {
                  htmlstr +='<li>'+array[index]+' </li>';
                });
                layer.open({
                  type: 1,
                  title: '错误的数据',
                  skin: 'layui-layer-demo', //样式类名
                  closeBtn: 1, //不显示关闭按钮
                  anim: 2,
                  shadeClose: true, //开启遮罩关闭
                  content: '<ul>'+htmlstr+'</ul>'
                });
              }
              table2.bootstrapTable('refresh');
            });
          });
          //物流单号导入 下册
          Upload.api.plupload($('.btn-importwl'), function (data, ret) {
            Fast.api.ajax({
              url: 'wx/wxorder/importwl',
              data: {file: data.url},
            }, function (data, ret) {
              if(data.length >= 1){
                var htmlstr = '';
                data.forEach(function (element, index, array) {
                  htmlstr +='<li>'+array[index]+' </li>';
                });
                layer.open({
                  type: 1,
                  title: '错误的数据',
                  skin: 'layui-layer-demo', //样式类名
                  closeBtn: 1, //不显示关闭按钮
                  anim: 2,
                  shadeClose: true, //开启遮罩关闭
                  content: '<ul>'+htmlstr+'</ul>'
                });
              }
              table2.bootstrapTable('refresh');
            });
          });
        });
      }
    },
    add: function () {
      Controller.api.bindevent();
    },
    config: function () {
      Controller.api.bindevent();
    },
    edit: function () {
      Controller.api.bindevent();
    },
    send: function () {
      var product = '';
      $('#product').change(function () {
        var status = $('#orderStatus').val();
        if(status == 1)
        {
          product = "《小学生绘本课堂》已发货，根据随书附带的流程，下载APP配合使用效果更佳！快递方式：XXXX，快递单号：XXXX。";
        }
        if(status == 2)
        {
          product = "《小学生绘本课堂》为您补寄的"+$(this).val()+"已发货，根据随书附带的流程，下载APP配合使用效果更佳！快递方式：XXXX，快递单号：XXXX。";
        }
        if(status == 3)
        {
          product = "《小学生绘本课堂》已发货，根据随书附带的流程，下载APP配合使用效果更佳！因"+$(this).val()+"缺货，于一周内为您补寄，盼理解。快递方式：XXXX，快递单号：XXXX。";
        }
        $('#c-import_note').val(product);
      });

      $('#orderStatus').change(function () {
        var status = $('#orderStatus').val();
        var product = $('#product').val();
        var html = '';
        if(status == 1)
        {
          html = "《小学生绘本课堂》已发货，根据随书附带的流程，下载APP配合使用效果更佳！快递方式：XXXX，快递单号：XXXX。";
        }
        if(status == 2)
        {
          html = "《小学生绘本课堂》为您补寄的"+product+"已发货，根据随书附带的流程，下载APP配合使用效果更佳！快递方式：XXXX，快递单号：XXXX。";
        }
        if(status == 3)
        {
          html = "《小学生绘本课堂》已发货，根据随书附带的流程，下载APP配合使用效果更佳！因"+product+"缺货，于一周内为您补寄，盼理解。快递方式：XXXX，快递单号：XXXX。";
        }
        $('#c-import_note').val(html);
      });
      Controller.api.bindevent();
    },

    api: {
      bindevent: function () {
        Form.api.bindevent($("form[role=form]"), function(data, ret){
          // Toastr.success(data);//成功
        }, function(data, ret){
          Toastr.error(ret.msg);//成功
          if(!data)  return false;
          layer.open({
            type: 1,
            title:'产品名称错误列表',
            skin: 'layui-layer-rim', //加上边框
            area: ['420px', '440px'], //宽高
            content: data
          },function (success,error) {

          });
        });
      },
      formatter:{
        css:function () {
            return {
              css:{
                "max-width":"350px !important",
                "overflow":"hidden",
                "white-space":"nowrap",
                "text-overflow":"ellipsis",
              }
            }
        }
      }
    }
  };
  return Controller;
});